
var pipetrisGlobals = {
  'currentPiece' : null,
  'nextPiece' : null,
  'paused' : false,
  'speed' : 400,
  'stopMovement' : false,
  'meldedCurrent' : false
};

function rotateRight() { pipetrisGlobals.currentPiece.rotateRight(); }
function rotateLeft() { pipetrisGlobals.currentPiece.rotateLeft(); }

function moveLeftStart() {
  pipetrisGlobals.stopMovement = false;
  pipetrisGlobals.currentPiece.moveLeft();
  setTimeout(moveLeftUpdate, 100);
}
function moveLeftUpdate() {
  if (pipetrisGlobals.stopMovement) { return; } 
  pipetrisGlobals.currentPiece.moveLeft();
  setTimeout(moveLeftUpdate, 100);
}

function moveRightStart() {
  pipetrisGlobals.stopMovement = false;
  pipetrisGlobals.currentPiece.moveRight();
  setTimeout(moveRightUpdate, 100);
}
function moveRightUpdate() {
  if (pipetrisGlobals.stopMovement) { return; } 
  pipetrisGlobals.currentPiece.moveRight();
  setTimeout(moveRightUpdate, 100);
}

function moveLeft() { pipetrisGlobals.currentPiece.moveLeft(); }
function moveRight() { pipetrisGlobals.currentPiece.moveRight(); }

function moveDownStart() { 
  pipetrisGlobals.stopMovement = false;
  pipetrisGlobals.currentPiece.drop(); 
  setTimeout(moveDownUpdate, 100);
}

function moveDownUpdate() {
  if (pipetrisGlobals.stopMovement) { return; } 
  pipetrisGlobals.currentPiece.drop();
  setTimeout(moveDownUpdate, 100);
}

function pause() {
  pipetrisGlobals.paused = !pipetrisGlobals.paused;
  if (!pipetrisGlobals.paused) {
    update();
  }

}

function handleKeyDown(e) {
//  window.alert('keydown: ' + e.keyCode);
  switch(e.keyCode) {
    case 37: 
      moveLeftStart();
      break;
    case 39: 
      moveRightStart();
      break;
    case 40:
      moveDownStart();
      break;
    case 68:
      rotateLeft();
      break;
    case 70:
      rotateRight();
      break;
  }
  Event.stop(e);
  return false;
}

function handleKeyUp(e) {
  debug('in handleKeyUP');
  switch(e.keyCode) {
    case 40:
      break;
  }
  pipetrisGlobals.stopMovement = true;
  Event.stop(e);
  return false; 
}

function newPiece() {
  if (pipetrisGlobals.currentPiece != null) { delete pipetrisGlobals.currentPiece; }
  pipetrisGlobals.currentPiece = new Piece();
  pipetrisGlobals.currentPiece.setTransform(3, 0, 0);
  pipetrisGlobals.currentPiece.set();
  pipetrisGlobals.meldedCurrent = false;
}


function advanceState() {

//  $('test_div').innerHTML = 'moving? ' + objectGlobals.gameBoard.moving; //dumpObj(objectGlobals.gameBoard, 'gb', '<br />', 1); 

  if (objectGlobals.gameBoard.piping) {
    if (objectGlobals.gameBoard.makePipes()) {
//$('test_div').innerHTML += (State.dropping + ' - from piping; ');
      setTimeout(debugAdvanceState, 1000);
      return objectGlobals.setState(State.dropping);
    }
  }

  if (objectGlobals.gameBoard.destroying) {
    objectGlobals.gameBoard.destroy(true); 
    objectGlobals.gameBoard.moving = true;
    objectGlobals.gameBoard.destroying = false;
//$('test_div').innerHTML += (State.checkState + '; - from destroying ');
    $('score_value').innerHTML = objectGlobals.gameBoard.score;
    $('lines_value').innerHTML = objectGlobals.gameBoard.lines;
    $('pipes_value').innerHTML = objectGlobals.gameBoard.pipeTotal;
    $('big_pipe_value').innerHTML = objectGlobals.gameBoard.bigPipe;
     
    return objectGlobals.setState(State.checkState);
  }

  if (objectGlobals.gameBoard.moving) {
    if (!objectGlobals.gameBoard.moveDown()) {
//$('test_div').innerHTML += (State.checkState + '; - from moving');
      return objectGlobals.setState(State.checkState);
    }
    else {
      if (objectGlobals.gameBoard.checkLines()) {
        window.alert('game over');
        return objectGlobals.setState(State.gameOver);
      }
      if (objectGlobals.gameBoard.piping) {
        objectGlobals.gameBoard.makePipes();
        debugAdvanceState();
//$('test_div').innerHTML += (State.DROPPING + '; - from inner pipping');
        return objectGlobals.setState(State.dropping);
      }
      if (objectGlobals.gameBoard.moving) {
        if (!objectGlobals.gameBoard.moveDown()) {
//$('test_div').innerHTML += (State.dropping + '; -from moving');
          debugAdvanceState();
          return objectGlobals.setState(State.dropping);
        }
        else {
          if (objectGlobals.gameBoard.checkLines()) {
            debugAdvanceState();
            window.alert('game over');
            return objectGlobals.setState(State.gameOver);
          }
          else {
//$('test_div').innerHTML += (State.dropping + '; -from not moving');
            return objectGlobals.setState(State.dropping);
          }
        }
      }
$('test_div').innerHTML += (State.nextPiece + '; - from after moving');
      return objectGlobals.setState(State.nextPiece);
    }
  }
   
$('test_div').innerHTML += (State.nextPiece + '; - from then end');
  
  return objectGlobals.setState(State.nextPiece); 
}

function setUpdate() { setTimeout(update, pipetrisGlobals.speed); }

function update() {

  if ((pipetrisGlobals.currentPiece != null) && (!pipetrisGlobals.currentPiece.drop())) {

    $('test_div').innerHTML += "melding!";

    if (pipetrisGlobals.meldedCurrent == false) {
      pipetrisGlobals.currentPiece.meld();
      pipetrisGlobals.meldedCurrent = true;
    }

    if (objectGlobals.gameBoard.checkLines()) {
      window.alert("game over");
    }

    if (debugAdvanceState() == State.nextPiece) {
      newPiece();
    }
  }

  if (!pipetrisGlobals.paused) {
    setTimeout(update, pipetrisGlobals.speed);
  }
}

function debugAdvanceState() {
  var state = advanceState();
//  $('test_div').innerHTML += (state + '; ');
  return state;
}

function debug(str) {
  $('test_div').innerHTML = str;
}

function debugBoard() {
  $('test_div').innerHTML = '';
  for( var j = 0; (j < 23); j++) {
    for( var i = 0; (i < 12); i++) {
      if (objectGlobals.gameBoard.board[i][j] != null) {
        objectGlobals.gameBoard.board[i][j].span.setAttribute('title', dumpObj(
          objectGlobals.gameBoard.board[i][j], 'b', "\n", 1));
        $('test_div').appendChild(objectGlobals.gameBoard.board[i][j].span);
        
      }
      else {
        var span = new Element('span');
        span.innerHTML = '0, ';
        $('test_div').appendChild(span);
      }
    }
    $('test_div').appendChild(new Element('br'));
  }
/*
  for( var j = 0; (j < 23); j++) {
    for( var i = 0; (i < 12); i++) {
      if (objectGlobals.gameBoard.board[i][j] != null) {
        $('test_div').innerHTML += objectGlobals.gameBoard.board[i][j].uuid;
        var elem = document.getElementById(objectGlobals.gameBoard.board[i][j].uuid);
        $('test_div').innerHTML += elem;
        elem = Element.extend(elem); 
        elem.setAttribute('uuid', objectGlobals.gameBoard.board[i][j].uuid);
        elem.observe('click', 
          objectGlobals.gameBoard.board[i][j].debugOnClick);
      }
    }
  }
*/
  $('test_div').innerHTML += 'done';

}


function onLoad() {
  // scroll to remove the address bar on the iPhone
  setTimeout(function() { window.scrollTo(0,1) }, 100);

  // button click event handlers
  Event.observe($('rotate_right_button'), 'click', rotateRight);
  Event.observe($('rotate_left_button'), 'click', rotateLeft);
  Event.observe($('move_right_button'), 'click', moveRight);
  Event.observe($('move_left_button'), 'click', moveLeft);
  Event.observe($('move_down_button'), 'mousedown', moveDownStart);
  Event.observe(window, 'mouseup', function () { pipetrisGlobals.stopMovement = true; });
  Event.observe($('pause_button'), 'click', pause);
  Event.observe($('debug_button'), 'click', debugBoard);
  Event.observe($('update_button'), 'click', update);
  Event.observe(window, 'keydown', handleKeyDown);
  Event.observe(window, 'keyup', handleKeyUp);
 

  pipetrisGlobals.currentPiece = new Piece();
  pipetrisGlobals.currentPiece.setTransform(3, 0, 0);
  pipetrisGlobals.currentPiece.set();

  setTimeout(update, pipetrisGlobals.speed);

  //window.alert($("#game_board").innerHTML);

/*
  for (var i=0; (i < 11); i++) {
    $("#game_board").html($("#game_board").html() + "<div class='block'></div>");
  }
*/

//  window.alert($("#game_board").html());
}

Event.observe(window, 'load', onLoad);
